﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using XichLoGreen.Models;
using PagedList;
using System.Web.Helpers;
using System.IO;
using System.Web.Script.Serialization;

namespace XichLoGreen.Controllers
{
    public class GreenNewsController : Controller
    {
        //
        // GET: /GreenNews/
		GreenIntities db = new GreenIntities();
        bool KTSession()
        {
            bool a = true;
            UserModel temp = (UserModel)Session["Account"];
            if (temp == null || temp.Type != UserType.ADMIN)
                a=false;
            return a;
        }
        public ActionResult Index(int? page)
        {
            if (!KTSession())
            {
                return RedirectToAction("Index", "Home");
            }
			var lstNews = db.News.ToList();
			int pageSize = 5;
			int pageNumber = (page ?? 1);
			return View(lstNews.ToPagedList(pageNumber, pageSize));
        }

		public ActionResult NewsManagement()
		{
            if (!KTSession())
            {
                return RedirectToAction("Index", "Home");
            }
			var lstNews = db.News.ToList();
			
			return View(lstNews);
		}

		//GET: /GreenNews/Edit/5
		public ActionResult Edit(int id)
		{
            if (!KTSession())
            {
                return RedirectToAction("Index", "Home");
            }
            NewsModel news = new NewsModel();
            if (id != -1)
                news = db.News.Find(id);
            else news =(NewsModel) Session["NewNews"];
			return View(news);
		}

		//
		//POST: /GreenNews/Edit/5
		[HttpPost]
		[AcceptVerbs(HttpVerbs.Post), ValidateInput(false)]
        public ActionResult Edit(NewsModel news, string submitButton, IEnumerable<HttpPostedFileBase> file, string picture, 
            string S1, string str_summary, string str_content, string str_imgComment)
		{
            if (!KTSession())
            {
                return RedirectToAction("Index", "Home");
            }
            string imgStr = picture;
			if((news.Title == "" || news.Title == null))
				return RedirectToAction("Edit", new { id = news.ID });

			if (submitButton == "Cancel")
				return RedirectToAction("NewsManagement");
			else
			{
				news.Picture = picture;
                news.Summary = str_summary;
                news.Content = str_content;
                news.ImageComment = str_imgComment;
				if (S1 != "") news.Content = S1;
				string physicalPath = HttpContext.Server.MapPath("~/Content/img/news_img/");

				for (int i = 0; i < Request.Files.Count; i++)
				{
					if (Request.Files[i].FileName == "" || Request.Files[i].FileName == null) break;
					string path = physicalPath + System.IO.Path.GetFileName(Request.Files[i].FileName);
					Request.Files[0].SaveAs(path);
					news.Picture = "../../Content/img/news_img/" + System.IO.Path.GetFileName(Request.Files[i].FileName);
                    imgStr = news.Picture;
				}

				if (ModelState.IsValid && submitButton == "Save")
				{
					db.Entry(news).State = System.Data.EntityState.Modified;
					db.SaveChanges();
					return RedirectToAction("NewsManagement");
				}
				else
				{
                    //db.Entry(news).State = System.Data.EntityState.Modified;
                    //db.SaveChanges();
                    NewsModel newsModel = new NewsModel();
                    newsModel.ID = -1;
                    newsModel.Author = news.Author;
                    if (S1 != "")
                        newsModel.Content = S1;
                    else newsModel.Content = news.Content;
                    newsModel.ImageComment = news.ImageComment; ;
                    newsModel.Picture = imgStr; 
                    newsModel.Source = news.Source; ;
                    newsModel.Summary = str_summary;
                    newsModel.Title = news.Title;
                    //db.News.Add(newsModel);
                    //db.Entry(newsModel).State = System.Data.EntityState.Added;
                    //db.SaveChanges();
                    Session["NewNews"] = newsModel; 
					return RedirectToAction("Preview", new { id = news.ID });
				}
			}
		}

		public ActionResult Preview(int id)
		{
            if (!KTSession())
            {
                return RedirectToAction("Index", "Home");
            }
            Session["OldID"] = id;
            NewsModel newsModel = (NewsModel)Session["NewNews"];
				
			return View(newsModel);
		}

		[HttpPost]
		public ActionResult Preview(string button)
		{
            if (!KTSession())
            {
                return RedirectToAction("Index", "Home");
            }
            NewsModel newNews = (NewsModel)Session["NewNews"];
            if (button == "Save")
            {
                NewsModel oldNews = db.News.Find(Session["OldID"]);
                
                oldNews.Author = newNews.Author;
                oldNews.Content = newNews.Content;
               
                oldNews.ImageComment = newNews.ImageComment;
                oldNews.Picture = newNews.Picture;
                oldNews.Source = newNews.Source;
                oldNews.Summary = newNews.Summary;
                oldNews.Title = newNews.Title;
                db.Entry(oldNews).State = System.Data.EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("NewsManagement");
            }
            else return RedirectToAction("Edit", new{id  = -1 });
		}

		//public bool HasFile(this HttpPostedFileBase file)
		//{
		//	return (file != null && file.ContentLength > 0) ? true : false;
		//}
		
    }
}
